package com.yuanlp.mobileplayer.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.yuanlp.mobileplayer.IMusicPlayerService;
import com.yuanlp.mobileplayer.R;
import com.yuanlp.mobileplayer.bean.MediaItem;
import com.yuanlp.mobileplayer.service.MusicPlayerService;
import com.yuanlp.mobileplayer.utils.LyrcUtils;
import com.yuanlp.mobileplayer.utils.Utils;
import com.yuanlp.mobileplayer.view.ShowlyrcView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;

import static android.content.ContentValues.TAG;

/**
 * Created by 原立鹏 on 2017/7/27.
 */

public class AudioPlayerAcivity extends Activity implements View.OnClickListener {

    private static final int UPDATE_SEEKBAR = 0;  //更新进度条时的handler消息
    private static final int SHOW_LYRC = 1;
    private ImageView iv_play_icon;
    private int position;  //获取从audiopager中从intent传过来的位置信息
    private ArrayList<MediaItem> medialist;

    private IMusicPlayerService mservice;

    private ImageView ivPlayIcon;
    private TextView tvSigner;
    private TextView tvSong;
    private TextView tvTime;
    private SeekBar seekbarAudio;
    private Button btAudioMode;
    private Button btAudioPre;
    private Button btAudioStartPause;
    private Button btAudioNext;
    private Button btLyrc;

    private boolean isPlaying;

    private MyBroadcast broadcast; //广播类实例



    private Utils utils;
    private boolean isNotifaction;  //判断是否是从notifaction那里传过来的intent
    private int currentposition;

    private ShowlyrcView showlyrcView;  //歌词区域的控件

    /**
     * Find the Views in the layout<br />
     * <br />
     * Auto-created on 2017-07-28 08:54:55 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    private void findViews() {
        System.out.println("初始化数据");
        ivPlayIcon = (ImageView)findViewById( R.id.iv_play_icon );
        tvSigner = (TextView)findViewById( R.id.tv_signer );
        tvSong = (TextView)findViewById( R.id.tv_song );
        tvTime = (TextView)findViewById( R.id.tv_time );
        seekbarAudio = (SeekBar)findViewById( R.id.seekbar_audio );
        btAudioMode = (Button)findViewById( R.id.bt_audio_mode );
        btAudioPre = (Button)findViewById( R.id.bt_audio_pre );
        btAudioStartPause = (Button)findViewById( R.id.bt_audio_start_pause );
        btAudioNext = (Button)findViewById( R.id.bt_audio_next );
        btLyrc = (Button)findViewById( R.id.bt_lyrc );

        btAudioMode.setOnClickListener( this );
        btAudioPre.setOnClickListener( this );
        btAudioStartPause.setOnClickListener( this );
        btAudioNext.setOnClickListener( this );
        btLyrc.setOnClickListener( this );

        showlyrcView= (ShowlyrcView) findViewById(R.id.showlyrcView);
    }

    /**
     * Handle button click events<br />
     * <br />
     * Auto-created on 2017-07-28 08:54:55 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    @Override
    public void onClick(View v) {
        if ( v == btAudioMode ) {
            // Handle clicks for btAudioMode
            getPlayMode();  //设置播放模式
        } else if ( v == btAudioPre ) {
            // Handle clicks for btAudioPre
//            position-=1;
//            if (position<0){
//                position=medialist.size()-1;
//            }
//            try {
//                MediaItem item=medialist.get(position);
//                tvSigner.setText(item.getArtist());
//                tvSong.setText(item.getName());
//                mservice.openAudio(position);
//            } catch (RemoteException e) {
//                e.printStackTrace();
//            }
            if (mservice!=null){
                try {
                    mservice.getPre();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        } else if ( v == btAudioStartPause ) {

            try {
                isPlaying=mservice.isPlaying();
                if (isPlaying){  //表示此时在播放，应该把图片切换为播放界面，然后暂停播放
                    mservice.pauseAudio();
                    btAudioStartPause.setBackgroundResource(R.drawable.bt_audio_start_selector);

                }else{
                    mservice.startAudio();
                    btAudioStartPause.setBackgroundResource(R.drawable.bt_audio_pause_selector);
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            // Handle clicks for btAudioStartPause
        } else if ( v == btAudioNext ) {
            // Handle clicks for btAudioNext
           if (mservice!=null){
               try {
                   mservice.getNext();
               } catch (RemoteException e) {
                   e.printStackTrace();
               }
           }

        } else if ( v == btLyrc ) {
            // Handle clicks for btLyrc
        }
    }

    private void getPlayMode() {
        try {
            int playMode=mservice.getPlayMode();
            if (playMode==MusicPlayerService.REPEAT_NORMAL){
                playMode=MusicPlayerService.REPEAT_SINGLE;  //切换为单曲循环,并把按钮图片切换

            }else if (playMode==MusicPlayerService.REPEAT_SINGLE){
                playMode=MusicPlayerService.REPEAT_ALL;  //如果为单曲循环，切换为循环播放

            }else if (playMode==MusicPlayerService.REPEAT_ALL){
                playMode=MusicPlayerService.REPEAT_NORMAL; //如果为循环播放，则切换为顺序播放，播放全部后，停止播放

            }else {
                playMode=MusicPlayerService.REPEAT_NORMAL; //如果为循环播放，则切换为顺序播放，播放全部后，停止播放
            }

            mservice.setPlayMode(playMode);
            setPlayMode();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    private void setPlayMode() {
        try {
            int playMode=mservice.getPlayMode();
            if (playMode==MusicPlayerService.REPEAT_NORMAL){
                btAudioMode.setBackgroundResource(R.drawable.bt_audio_mode_normal_selector);
                Toast.makeText(this,"顺序播放",Toast.LENGTH_SHORT).show();

            }else if (playMode==MusicPlayerService.REPEAT_SINGLE){
                btAudioMode.setBackgroundResource(R.drawable.bt_audio_mode_single_selector);
                Toast.makeText(this,"单曲循环",Toast.LENGTH_SHORT).show();

            }else if (playMode==MusicPlayerService.REPEAT_ALL){
                btAudioMode.setBackgroundResource(R.drawable.bt_audio_mode_all_selector);
                Toast.makeText(this,"循环播放",Toast.LENGTH_SHORT).show();

            }


        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void checkPlayMode(){
        try {
            int playMode=mservice.getPlayMode();
            if (playMode==MusicPlayerService.REPEAT_NORMAL){
                btAudioMode.setBackgroundResource(R.drawable.bt_audio_mode_normal_selector);

            }else if (playMode==MusicPlayerService.REPEAT_SINGLE){
                btAudioMode.setBackgroundResource(R.drawable.bt_audio_mode_single_selector);

            }else if (playMode==MusicPlayerService.REPEAT_ALL){
                btAudioMode.setBackgroundResource(R.drawable.bt_audio_mode_all_selector);

            }


        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case UPDATE_SEEKBAR:
                    //1 得到当前进度
                    try {
                        int currentPosition=mservice.getCurrentPosition();

                        seekbarAudio.setProgress(currentPosition);
                        String time=utils.stringForTime(currentPosition)+"/"+utils.stringForTime((int) mservice.getDuration());
                        tvTime.setText(time);

                        handler.removeMessages(UPDATE_SEEKBAR);

                        /**
                         * 每秒刷新下进度条
                         */
                        handler.sendEmptyMessageDelayed(UPDATE_SEEKBAR,1000);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }

                    break;
                case SHOW_LYRC:

                    //1、获取当前进度
                    try {
                        int currentPosition=mservice.getCurrentPosition();
                        //2、根据当前进度，获取歌词
                        showlyrcView.setShowNextLyrc(currentPosition);
                        //3、实时发消息去更新歌词
                        handler.removeMessages(SHOW_LYRC);
                        handler.sendEmptyMessage(SHOW_LYRC);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: 音乐播放activity被创建了");
        System.out.println("音乐播放activity被创建了");
        setContentView(R.layout.activity_audioplayer);


        utils=new Utils();
        /**
         * 初始化音乐界面的图片变化的布局
         */
        initView();

        /**
         * 实例化布局里的各个控件
         */
        findViews();

        //注册广播
        registerBorader();

        //注册eventbus
        EventBus.getDefault().register(this);  //this代表当前类

        /**
         * 根据位置获取音乐
         */

            getData();



        /**
         * 绑定服务并启动服务
         */
        bindAndStartService();

        seekbarAudio.setOnSeekBarChangeListener(new MyOnSeekBarChangeListener());
    }

    class MyOnSeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {


        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            if (fromUser){
                try {
                    mservice.seekTo(progress);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }


        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    }

    private void bindAndStartService() {
        System.out.println("绑定服务 bindService。。。。。。");
        Intent intent=new Intent(this, MusicPlayerService.class);
        //intent.setAction("com.yuanlp.mobilePlayer");
        Bundle bundle=new Bundle();
        bundle.putSerializable("medialist",medialist);
        intent.putExtras(bundle);
        startService(intent);  //不至于多次实例化服务对象
        //System.out.println("数量是多少"+medialist.size());
        bindService(intent,conn,BIND_AUTO_CREATE);
        System.out.println("绑定后，再启动服务");
        // Bundle bundle=new Bundle();
        startService(intent);  //不至于多次实例化服务对象

//        bundle.putSerializable("medialist",medialist);
//        intent.putExtras(bundle);

    }

    /**
     * 与服务创建连接
     */
    private ServiceConnection conn=new ServiceConnection() {
        /**
         * 当连接成功时，回调方法
         * @param name
         * @param service
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("成功连接。。。");
            mservice=IMusicPlayerService.Stub.asInterface(service);

            if (mservice!=null){
                try {

                    if (!isNotifaction){  //不是 从状态栏里过来的,是从列表过来的，那么重新播放
                        System.out.println("成功连接后，service不为空");
                        mservice.openAudio(position);
                    }else{
                        showViewData();

                    }
//                    MediaItem item=medialist.get(position);
//                    String artist=item.getArtist();
//                    String song=item.getName();
//                    tvSigner.setText(artist);
//                    tvSong.setText(song);

                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * 当连接失败时回调方法
         * @param name
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("连接失败。。。");
            try {
                if (mservice!=null){
                    mservice.stopAudio();
                    mservice=null;
                }

            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    };

    private void getData() {
        System.out.println("获取数据------");
        medialist=new ArrayList<MediaItem>();

        medialist= (ArrayList<MediaItem>) getIntent().getSerializableExtra("mediallist");
        System.out.println("当前的list数量------------------------"+medialist.size());
        //得到intent的数据


        isNotifaction = getIntent().getBooleanExtra("Notifaction",false);
        if (!isNotifaction){
            position = getIntent().getIntExtra("position", 0);
        }
        //currentposition = getIntent().getIntExtra("currentPosition",0);
        System.out.println("传到activity里获取的当前进度isNotifaction是------------"+isNotifaction);
    }

    private void initView() {
        System.out.println("初始化跳动的图片");
        iv_play_icon= (ImageView) findViewById(R.id.iv_play_icon);
        iv_play_icon.setBackgroundResource(R.drawable.animation_list);
        AnimationDrawable rocketAnimation= (AnimationDrawable) iv_play_icon.getBackground();
        rocketAnimation.start();
    }


    /**
     * 广播接收，接受来自service里开始播放后发送的广播
     */
    class MyBroadcast extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            /**
             * 接收到广播后，显示歌曲名、歌曲时间等信息
             */
            showViewData();
            checkPlayMode();
        }
    }

    /**
     * 订阅eventbus
     */
    @Subscribe(threadMode=ThreadMode.MAIN,sticky = false,priority = 99)
    public void showData(MediaItem item) {

        showLyrc();  //去获取MP3文件的路径然后获取歌词文件，并解析歌词，最终显示歌词
        showViewData();
        checkPlayMode();
    }

    /**
     * 去获取MP3文件的路径然后获取歌词文件，并解析歌词，最终显示歌词
     */
    public void showLyrc() {
        LyrcUtils lyrcUtils=new LyrcUtils();
        try {
            //得到录音文件的地址
            String path=mservice.getAudioPath();
            path=path.substring(0,path.lastIndexOf("."));
            File file=new File(path+".lrc");  //先去查找lrc格式的歌词文件
            if (!file.exists()){
                file=new File(path+".txt");  //拼一个TXT格式的歌词文件
            }
            lyrcUtils.readLyrcFile(file);
            showlyrcView.setLyrcs(lyrcUtils.getLyrcs());
            if (lyrcUtils.isExistsLyrc()){
                //存在歌词，才发消息，否则不发消息
                handler.sendEmptyMessage(SHOW_LYRC);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }


    }

    /**
     * 接收到广播后，显示歌曲名、歌曲时间等信息
     */
    private void showViewData() {
        try {
            tvSigner.setText(mservice.getSinger());
            tvSong.setText(mservice.getSong());

            //设置进度条
            seekbarAudio.setMax((int) mservice.getDuration());
            handler.sendEmptyMessage(UPDATE_SEEKBAR);

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 注册广播，接收service发送的广播
     */
    private void registerBorader() {
        System.out.println("注册广播");
        //这里取消广播，利用eventbus来替代
//        broadcast=new MyBroadcast();
//        IntentFilter intentfilter=new IntentFilter();
//        intentfilter.addAction(MusicPlayerService.OPENAUDIOPLAYER);
//        registerReceiver(broadcast,intentfilter);

        //eventbus注册


    }

    /**
     * 在onDestroy里取消注册广播
     */
    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null);  //推出activity时，移除所有消息
//        if (broadcast!=null){
//            unregisterReceiver(broadcast);
//            broadcast=null;  //这里为什么把广播设置为null，因为取消注册后，垃圾回收器不一定马上回收广播，如果设置为null，那么会优先回收这个
//        }

        //取消注册eventbus
        EventBus.getDefault().unregister(this);


        //解绑服务
        if(conn!=null){
            unbindService(conn);
        }
        super.onDestroy();
    }
}
